package com.lottery.im.api.observer;

import android.app.Activity;
import android.text.TextUtils;
import android.widget.Toast;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.ApiCode;
import com.lottery.im.api.result.ApiListResult;
import com.lottery.im.widget.dialog.LoadingDialogUtil;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.List;
import org.json.JSONException;
import retrofit2.HttpException;

/**
 * Created by lianwufeng on 2017/9/15.
 *
 * 加载框 + 错误提示
 * 返回 列表类型
 */

public abstract class ShowTipListObserver<T> implements io.reactivex.Observer<ApiListResult<T>> {

  private Activity mActivity;

  public ShowTipListObserver(Activity activity) {
    this.mActivity = activity;
    onStart();
  }

  @Override public void onSubscribe(@NonNull Disposable d) {

  }

  @Override public void onNext(ApiListResult<T> tApiListResult) {

    if (tApiListResult.getReturnCode().equals(ApiCode.SUCCESS_CODE)) {
      onSuccess(tApiListResult.getReturnList());
    } else {
      onFail(tApiListResult.getReturnCode(), tApiListResult.getReturnMessage());
    }
  }

  @Override public void onError(@NonNull Throwable e) {
    if (e instanceof HttpException) {
      onException(MyApplication.getInstance().getResources().getString(R.string.error_message));
    } else if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
      onException(MyApplication.getInstance().getResources().getString(R.string.error_message));
    } else if (e instanceof JSONException || e instanceof ParseException) {

    } else if (e instanceof UnknownHostException) {
      onException(MyApplication.getInstance().getResources().getString(R.string.error_message));
    } else {
      if (!TextUtils.isEmpty(e.getMessage())) {
        onException(e.getMessage());
      } else {
        onException(MyApplication.getInstance().getResources().getString(R.string.error_message));
      }
    }
    onFinish();
  }

  @Override public void onComplete() {
    onFinish();
  }

  // 开始
  public void onStart() {
    LoadingDialogUtil.showProgressDialog(mActivity);
  }

  // 请求成功
  public abstract void onSuccess(List<T> t);

  // 请求成功 + 但是获取数据失败 （如：密码错误、身份失效）
  public void onFail(String code, String msg) {
    Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
  }

  // 请求异常
  public void onException(String msg) {
    Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
  }

  // 请求完成
  public void onFinish() {
    LoadingDialogUtil.cancelProgressDialog();
  }
}